package com.example.docmanagement.security;

import com.example.docmanagement.entity.User;
import com.example.docmanagement.repository.UserRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 用户详情服务实现
 * Spring Security 用于加载用户信息
 */
@Service
@RequiredArgsConstructor
public class UserDetailsServiceImpl implements UserDetailsService {

    private final UserRepository userRepository;

    /**
     * 加载用户详情
     * 参数可以是邮箱或用户名
     */
    @Override
    @Transactional(readOnly = true)
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 通过邮箱或用户名查找用户
        User user = userRepository.findByEmailOrUsername(username, username)
                .orElseThrow(() -> new UsernameNotFoundException("用户不存在：" + username));

        // 检查用户状态
        if (user.getDeletedAt() != null) {
            throw new UsernameNotFoundException("用户已被删除");
        }

        if (!"active".equals(user.getStatus())) {
            throw new UsernameNotFoundException("用户状态异常：" + user.getStatus());
        }

        List<GrantedAuthority> authorities = new ArrayList<>();

        if (user.getRole() != null && user.getRole().getName() != null) {
            authorities.add(new SimpleGrantedAuthority("ROLE_" + user.getRole().getName().toUpperCase()));

            if (user.getRole().getPermissions() != null) {
                authorities.addAll(
                        user.getRole().getPermissions().stream()
                                .map(permission -> new SimpleGrantedAuthority(permission.getName()))
                                .collect(Collectors.toList())
                );
            }
        } else {
            authorities.add(new SimpleGrantedAuthority("ROLE_USER"));
        }

        // 返回包含角色和权限的用户详情（使用邮箱作为登录凭证）
        return org.springframework.security.core.userdetails.User.builder()
                .username(user.getEmail())
                .password(user.getEncryptedPassword())
                .authorities(authorities)
                .accountExpired(false)
                .accountLocked(false)
                .credentialsExpired(false)
                .disabled(false)
                .build();
    }
}
